package model

import (
	"fmt"
	"gorm.io/gorm"
)

type Link struct {
	ID      int
	GroupID int `gorm:"index"`
	Start   string
	Stop    string
	Url     string
}

type Group struct {
	ID   int
	Name string
}

func (db *DB) GetGroup(id int) (g *Group, err error) {
	g = &Group{}
	err = db.db.Where("id=?", id).First(&g).Error
	if err != nil {
		return nil, err
	} else {
		return g, nil
	}
}

func (db *DB) GetGroups() (gs []*Group, err error) {
	err = db.db.Order("id desc").Find(&gs).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return gs, nil
}

func (db *DB) SaveGroup(g *Group) error {
	err := db.db.Save(g).Error
	if err != nil {
		return err
	}
	return db.reloadGroup(g.ID)
}

func (db *DB) DeleteGroup(id int) error {
	if id == 1 {
		return fmt.Errorf("默认分组不可删除")
	}
	var total int64
	err := db.db.Model(&Link{}).Where("group_id=?", id).Count(&total).Error
	if err != nil {
		return err
	}
	if total > 0 {
		return fmt.Errorf("需要先删除该组下的所有跳转地址")
	}
	err = db.db.Delete(&Group{ID: id}).Error
	if err != nil {
		return err
	}
	db.delCache(id)
	return nil
}

func (db *DB) GetLinks(groupID int) (ds []*Link, err error) {
	err = db.db.Where("group_id=?", groupID).Order("id desc").Find(&ds).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return ds, nil
}

func (db *DB) SaveLink(d *Link) (err error) {
	err = db.db.Save(d).Error
	if err != nil {
		return err
	}
	return db.reloadGroup(d.GroupID)
}

func (db *DB) DeleteLinks(groupID int, ids []int) (err error) {
	res := db.db.Where("group_id=? AND id in (?)", groupID, ids).Delete(&Link{})
	if res.Error != nil {
		return err
	}
	return db.reloadGroup(groupID)
}
